import Vue from "vue";
import VueRouter from "vue-router";

import Login from "@/views/login/index.vue";
import Layout from "@/views/layout/index.vue";
import Myorder from "@/views/myorder";
import Pay from "@/views/pay/index.vue";
import Prodetail from "@/views/prodetail";
import Search from "@/views/search/index.vue";
import SearchList from "@/views/search/list.vue";

import Home from "@/views/layout/home.vue";
import Category from "@/views/layout/category.vue";
import Cart from "@/views/layout/cart.vue";
import User from "@/views/layout/user.vue";

import store from "@/store";
Vue.use(VueRouter);

const routes = [
  {
    path: "/",
    component: Layout,
    redirect: "/home",
    children: [
      { path: "/home", component: Home },
      { path: "/category", component: Category },
      { path: "/cart", component: Cart },
      { path: "/user", component: User },
    ],
  },
  { path: "/login", component: Login },
  { path: "/myorder", component: Myorder },
  { path: "/pay", component: Pay },
  { path: "/prodetail/:id", component: Prodetail },
  { path: "/search", component: Search },
  { path: "/searchlist", component: SearchList },
];

const router = new VueRouter({
  mode: "hash",
  base: process.env.BASE_URL,
  routes,
});
// 全局前置守卫
// 定义一个数组，专门用户存放所有需要权限访问的页面
const authUrls = ["/myorder", "/pay"];
router.beforeEach((to, from, next) => {
  if (!authUrls.includes(to.path)) {
    // 非权限页面直接放行
    next();
    return;
  }
  // 权限页面需要判断是否登录
  const token = store.getters.token;
  if (token) {
    next();
  } else {
    next("/login");
  }
});
export default router;
